package com.atguigu.gmall.order.controller;


import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {



    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderService orderService;


    //
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(name = "orderId") Long orderId){

        return orderService.getOrderInfo(orderId);
    }


    //结算
    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request){
        Map result = new HashMap<>();
        String userId = AuthContextHolder.getUserId(request);
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);

        List<OrderDetail> detailArrayList = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setSkuId(cartInfo.getSkuId());
            return orderDetail;
        }).collect(Collectors.toList());
        result.put("detailArrayList",detailArrayList);
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        result.put("userAddressList",userAddressList);

        long totalNum = detailArrayList.stream()
                .collect(Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
        double totalAmount = detailArrayList.stream().collect(Collectors.summarizingDouble(orderDetail -> {
            return orderDetail.getOrderPrice().doubleValue()*orderDetail.getSkuNum();
        })).getSum();
        System.out.println(totalNum);
        result.put("totalNum",totalNum);
        result.put("totalAmount",totalAmount);
        //流水号
        String tradeNo = orderService.tradeNo(userId);
        result.put("tradeNo",tradeNo);
        return Result.ok(result);
    }

    //
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,String tradeNo,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        Boolean flag = orderService.checkTradeNo(userId,tradeNo);
        if(!flag){
            return Result.fail().message("不能重复提交订单");
        }
        //删除TradeNo
        orderService.deleteTradeNo(userId);
        // 验证库存
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            Boolean isStock = orderService.checkStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if(!isStock){
                return Result.fail().message(orderDetail.getSkuName() + "库存不足");
            }
        }
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderService.addOrder(orderInfo);
        return Result.ok(orderId);
    }
}
